package com.mallcai.bigdata.ladon.datasource;

import com.cake.bigdata.starter.exception.category.BusinessException;
import com.mallcai.bigdata.ladon.dpl.entity.common.Datasource;
import com.mallcai.bigdata.ladon.dpl.vo.DatasourceType;
import org.apache.commons.lang3.StringUtils;
import tk.mybatis.mapper.util.Assert;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by oneape<oneape15@163.com>
 * Created 2019-06-04 22:03.
 * Modify:
 */
public class DatasourceFactory {

    private static Map<String, AbstractDataSource> pools = new HashMap<>();

    private static AbstractDataSource initDataSource(Datasource ds) {
        DatasourceType dt = DatasourceType.getByCode(ds.getType());
        if (dt == null) {
            throw new BusinessException("不支持的数据源~");
        }
        if (dt == DatasourceType.ElasticSearch) {
            return new ElasticsearchDataSource(ds);
        } else if (dt == DatasourceType.MySQL) {
            return new MySQLDataSource(ds);
        }

        return null;
    }

    public synchronized static AbstractDataSource getDataSource(Datasource ds) {
        Assert.isTrue(ds != null, "数据源信息为NULL。");
        if (StringUtils.isBlank(ds.getJdbcUrl())) {
            return null;
        }

        if (pools.containsKey(ds.getJdbcUrl())) {
            return pools.get(ds.getJdbcUrl());
        }

        AbstractDataSource dataSource = initDataSource(ds);
        if (dataSource != null) {
            pools.put(ds.getJdbcUrl(), dataSource);
            return dataSource;
        }

        return null;
    }

}
